package com.itheima.search.listener;

import com.alibaba.fastjson.JSON;
import com.itheima.common.constants.KafkaConstants;
import com.itheima.model.book.dtos.BookEventDto;
import com.itheima.search.service.BookIndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * 图书事件监听器
 * 监听Kafka中的图书事件，同步更新Elasticsearch索引
 * 
 * @author itheima
 */
@Slf4j
@Component
public class BookEventListener {

    @Autowired
    private BookIndexService bookIndexService;

    /**
     * 监听图书事件
     * 处理图书的新增、更新、删除事件
     */
    @KafkaListener(
        topics = KafkaConstants.BookTopics.BOOK_EVENTS,
        groupId = KafkaConstants.ConsumerGroups.SEARCH_SERVICE
    )
    public void handleBookEvent(String message) {
        try {
            log.info("接收到图书事件消息: {}", message);
            
            BookEventDto event = JSON.parseObject(message, BookEventDto.class);
            if (event == null || event.getEventType() == null) {
                log.warn("图书事件消息格式错误: {}", message);
                return;
            }

            // 根据事件类型处理
            switch (event.getEventType()) {
                case BOOK_CREATED:
                    // 新增图书：添加到ES索引
                    handleBookCreated(event);
                    break;
                    
                case BOOK_UPDATED:
                    // 更新图书：更新ES索引
                    handleBookUpdated(event);
                    break;
                    
                case BOOK_DELETED:
                    // 删除图书：从ES索引中删除
                    handleBookDeleted(event);
                    break;
                    
                case BOOKS_BATCH_DELETED:
                    // 批量删除：暂时按单个删除处理
                    handleBookDeleted(event);
                    break;
                    
                default:
                    log.warn("未知的图书事件类型: {}", event.getEventType());
            }
            
        } catch (Exception e) {
            log.error("处理图书事件失败: message={}", message, e);
            // 这里可以考虑重试机制或将失败消息存入死信队列
        }
    }

    /**
     * 处理图书新增事件
     */
    private void handleBookCreated(BookEventDto event) {
        try {
            log.info("处理图书新增事件: bookId={}, title={}", event.getBookId(), event.getBookTitle());
            // 从数据库查询完整图书信息并添加到ES
            bookIndexService.addBookToIndex(event.getBookId());
            log.info("图书已添加到ES索引: bookId={}", event.getBookId());
        } catch (Exception e) {
            log.error("添加图书到ES索引失败: bookId={}", event.getBookId(), e);
        }
    }

    /**
     * 处理图书更新事件
     */
    private void handleBookUpdated(BookEventDto event) {
        try {
            log.info("处理图书更新事件: bookId={}, title={}", event.getBookId(), event.getBookTitle());
            // 从数据库查询最新图书信息并更新ES
            bookIndexService.updateBookInIndex(event.getBookId());
            log.info("图书已更新ES索引: bookId={}", event.getBookId());
        } catch (Exception e) {
            log.error("更新图书ES索引失败: bookId={}", event.getBookId(), e);
        }
    }

    /**
     * 处理图书删除事件
     */
    private void handleBookDeleted(BookEventDto event) {
        try {
            log.info("处理图书删除事件: bookId={}, title={}", event.getBookId(), event.getBookTitle());
            // 从ES中删除图书索引
            bookIndexService.deleteBookFromIndex(event.getBookId());
            log.info("图书已从ES索引中删除: bookId={}", event.getBookId());
        } catch (Exception e) {
            log.error("从ES索引中删除图书失败: bookId={}", event.getBookId(), e);
        }
    }
}

